package com.tengju.bff.interfaces.covercharge.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
@Slf4j
public class ThreadPoolExecutorConfig {

    @Bean
    public ThreadPoolExecutor initThreadPoolExecutor() {
        //核心CPU数量
        int coreSize = Runtime.getRuntime().availableProcessors();
        //核心Thread的Max比率
        int maxPoolSize = Math.round(((float) (coreSize * 80)) / 10);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(coreSize, maxPoolSize, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(1000), new RejectPolicy());
        threadPoolExecutor.prestartCoreThread();

        return threadPoolExecutor;
    }

    private class RejectPolicy implements RejectedExecutionHandler {
        private RejectPolicy() {
        }

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            log.warn("试算平衡线程池队列任务已满,请检查配置是否合理");
        }
    }

}
